package 并发编程15.线程池;

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 四种饱和策略 应对线程池溢出的方案
 *
 * @author idea
 * @data 2019/2/6
 */
public class Test {

    /**
     * 直接抛出异常
     */
    private ThreadPoolExecutor.AbortPolicy abortPolicy = new ThreadPoolExecutor.AbortPolicy();

    /**
     * 只用调用者的线程所在线程来执行任务
     */
    private ThreadPoolExecutor.CallerRunsPolicy callerRunsPolicy = new ThreadPoolExecutor.CallerRunsPolicy();

    /**
     * 丢弃队列里面最近的一个任务，并且执行当前任务
     */
    private ThreadPoolExecutor.DiscardOldestPolicy discardOldestPolicy = new ThreadPoolExecutor.DiscardOldestPolicy();

    /**
     * 不处理，不丢弃
     */
    private ThreadPoolExecutor.DiscardPolicy discardPolicy = new ThreadPoolExecutor.DiscardPolicy();

    /**
     * 构建一个普通的线程池
     */
    public void test1() {
        ThreadPoolExecutor threadPoolExecutor =
                new ThreadPoolExecutor(2, 2, 10, TimeUnit.SECONDS, new LinkedBlockingQueue<>());

    }

    /**
     * 构建单个线程池 饱和策略：直接拒绝执行
     */
    public void test2() {
        ThreadPoolExecutor threadPoolExecutor =
                new ThreadPoolExecutor(2, 2, 10, TimeUnit.SECONDS, new LinkedBlockingQueue<>(), abortPolicy);

    }

    /**
     * 构建单个线程池 饱和策略：强制让当前调用者所在的线程来执行
     */
    public void test3() {
        ThreadPoolExecutor threadPoolExecutor =
                new ThreadPoolExecutor(2, 2, 10, TimeUnit.SECONDS, new LinkedBlockingQueue<>(), callerRunsPolicy);

    }

    /**
     * 构建单个线程池 饱和策略：抛弃原有的某一个线程
     */
    public void test4() {
        ThreadPoolExecutor threadPoolExecutor =
                new ThreadPoolExecutor(2, 2, 10, TimeUnit.SECONDS, new LinkedBlockingQueue<>(), discardOldestPolicy);

    }

    /**
     * 构建单个线程池 饱和策略：直接抛弃
     */
    public void test5() {
        ThreadPoolExecutor threadPoolExecutor =
                new ThreadPoolExecutor(2, 2, 10, TimeUnit.SECONDS, new LinkedBlockingQueue<>(), discardPolicy);

    }
}

class TestThread implements Runnable {

    @Override
    public void run() {
        System.out.println("this is " + Thread.currentThread().getName());
    }
}
